<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/31
 * Time: 19:08
 */
include "config.php";

session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){

    if(!empty($_REQUEST["pid"]) && !empty($_REQUEST["title"]) && !empty($_REQUEST["price"]) && !empty($_REQUEST["mainImg"]) && !empty($_REQUEST["num"])){

        $pid = $_REQUEST["pid"];
        $title = $_REQUEST["title"];
        $price = $_REQUEST["price"];
        $name = $_SESSION["ifLogin"]["uname"];
        $img = $_REQUEST["mainImg"];
        $num = $_REQUEST["num"];
        $total = $price * $num;

        //1.读取数据库 的数据 根据 用户u_name,产品的g_id,作为查询条件,查看是否存在

        $extisSQL = "SELECT * FROM fashionshopping.goodinfo WHERE u_name=? AND g_id=?";
        $stmt = $conn->prepare($extisSQL);
        $stmt->bind_param("si", $name, $pid);
        $stmt->execute();
        $resultQuery = $stmt->get_result();
        if($resultQuery->num_rows>=1){
            //2. 存在
            // 数量与金额进行修改
            //修改,要根据 当前的购买人与产品id,进行修改 数量与总金额
            $updateSQL="UPDATE fashionshopping.goodinfo SET p_num=p_num +? ,p_total=p_num * p_price WHERE u_name=? AND g_id=?";

            $stmt = $conn->prepare($updateSQL);
            $stmt->bind_param("isi", $num, $name,$pid);
            $stmt->execute();
            if($stmt->affected_rows>=1){
                print_r(json_encode(Array("status" => 1, "msg" => "u修改成功")));
            }else{
                print_r(json_encode(Array("status" =>0, "msg" => "u修改失败")));
            }


        }else{
            //3.不存在, 插入 用户id,产品id,产品名称,产品价格,产品数量,产品图片

            $insertSQL="INSERT INTO fashionshopping.goodinfo(`p_title`,`p_price`,`p_img`,`u_name`,`g_id`,`p_total`,`p_num` )VALUES(?,?,?,?,?,?,?)";
            $stmt = $conn->prepare($insertSQL);
            $stmt->bind_param("ssssisi",$title,$price,$img,$name,$pid,$total,$num);
            $stmt->execute();
            if($stmt->affected_rows>=1){
                print_r(json_encode(Array("status" => 1, "msg" => "i插入成功")));
            }else{
                print_r(json_encode(Array("status" =>0, "msg" => "i插入失败")));
            }
        }

        $stmt->close();
        $conn->close();

    } else {
        print_r(json_encode(Array("status" => 0, "msg" => "参数不合法")));
    }


}